<template>
	<view class="pick-speaker">
		<view class="main-tabbar" v-if="tabbarAc == 1">
			<view :class="['tabbar-item', tabbarAc2 == item.id ? 'ac' : '']" v-for="(item, index) in tabbarList2" :key="item.id" @click="changeTabbarAc2({ item, index })">
				<view class="text">{{ item.fieldName }}</view>
			</view>
		</view>
		<view class="main-content">
			<scroll-view scroll-y :scroll-into-view="audioListLeft1" @scroll="contentListScroll" class="scroll_view" scroll-with-animation>
				<view class="audio-list-kong" v-if="tabbarAc == 1 && yushe.length == 0">
					<view class="text">暂无数据</view>
				</view>
				<view class="audio-list-kong" v-if="tabbarAc == 2 && geren.length == 0">
					<view class="text">暂无数据</view>
				</view>
				<view class="audio-list contentList" v-if="tabbarAc == 1">
					<view :class="['audio-item', item.dubId == selectItem.dubId ? 'ac' : '']" :id="'audioItem' + item.dubId" v-for="(item, index) in yushe" :key="item.dubId">
						<view class="left">
							<view class="pic-box">
								<image class="audio-pic" mode="" :src="item.headerImg || imgPath + 'createAvatar/audioMan.png'"></image>
								<view class="playStatusIcon" @tap.stop="pickShiTingItem({ item, index })">
									<image v-if="item.dubId == shiTingItem.dubId" class="icon playing" :src="imgPath + 'index/playing.svg'" mode="widthFix"></image>
									<image v-else class="icon played" :src="imgPath + 'index/played.svg'" mode="widthFix"></image>
								</view>
							</view>
							<view class="date-time">
								<view class="date">{{ item.dubName }}</view>
							</view>
							<view class="useBtn" @tap.stop="pickContentItem({ item, index })">
								<view class="useBtn-text">{{ item.dubId != selectItem.dubId ? "使用" : "取消" }}</view>
							</view>
						</view>
						<view class="right">
							<view class="useBtn" @tap.stop="pickShiTingItem({ item, index })">
								<view class="useBtn-text">{{ item.dubId != shiTingItem.dubId ? "试听" : "停止" }}</view>
							</view>
						</view>
					</view>
				</view>

				<view class="audio-list contentList" v-if="tabbarAc == 2">
					<view class="audio-item" v-for="(item, index) in geren" :key="index">
						<view class="left">
							<view class="pic-box">
								<image class="audio-pic" :src="imgPath + 'createAvatar/music&audio.svg'" mode=""></image>
								<view class="playStatusIcon">
									<svg v-if="false" t="1711093125129" class="icon playing" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3767" width="200" height="200">
										<path
											d="M384 256a42.666667 42.666667 0 0 0-42.666667-42.666667H298.666667a42.666667 42.666667 0 0 0-42.666667 42.666667v554.666667a42.666667 42.666667 0 0 0 42.666667 42.666666h42.666666a42.666667 42.666667 0 0 0 42.666667-42.666666V256z m384 0a42.666667 42.666667 0 0 0-42.666667-42.666667h-42.666666a42.666667 42.666667 0 0 0-42.666667 42.666667v554.666667a42.666667 42.666667 0 0 0 42.666667 42.666666h42.666666a42.666667 42.666667 0 0 0 42.666667-42.666666V256z"
											fill="rgba(255,255,255,0.86)"
											p-id="3768"
										></path>
									</svg>
									<svg v-else t="1711092755343" class="icon played" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2797" width="200" height="200">
										<path d="M755.552 495.36l-384-296.672a31.936 31.936 0 0 0-51.552 25.28v593.504a32 32 0 0 0 51.552 25.28l384-296.704a32 32 0 0 0 0-50.656" fill="rgba(255,255,255,0.86)" p-id="2798"></path>
									</svg>
								</view>
							</view>
							<view class="date-time">
								<view class="date">{{ item.matterName }}</view>
								<!-- <view class="date">{{item.updateTime.split(' ')[0]}}</view>
							<view class="time">{{item.updateTime.split(' ')[1]}}</view> -->
								<view class="time">{{ item.durationStr }}</view>
							</view>
						</view>
						<view class="right">
							<!-- <view class="time" style="margin-right: 2vw;">{{item.durationStr}}</view> -->
							<image class="icon" :src="imgPath + 'createAvatar/delAudio.svg'" mode=""></image>
							<view class="useBtn" @tap="pickContentItem({ item, index })">
								<view class="useBtn-text">{{ item.matterUrl != selectItem.matterUrl ? "使用" : "已使用" }}</view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>

			<view class="textStyle">
				<view class="textStyle-item">
					<view class="label">语速</view>
					<view class="r-c slider-box">
						<slider class="slider" :value="speed" @change="changeSpeedsize" step="0.01" min="0.5" max="2" show-value />
					</view>
				</view>
				<view class="textStyle-item">
					<view class="label">速调</view>
					<view class="r-c slider-box">
						<slider class="slider" :value="pitch" @change="changePitchsize" step="1" :min="-10" max="10" show-value />
					</view>
				</view>
				<view class="textStyle-item">
					<view class="label">音量</view>
					<view class="r-c slider-box">
						<slider class="slider" :value="volume" @change="changeVolumesize" step="1" :min="0" :max="100" show-value />
					</view>
				</view>
			</view>
		</view>
		<view class="main-selectItem" v-if="shiTingItem.dubId" v-show="0">
			<view class="item-info">
				<view class="left">
					<view class="pic">
						<image class="audio-pic" :src="shiTingItem.headerImg || imgPath + 'createAvatar/audioMan.png'" mode=""></image>
					</view>
					<view class="text">正在试听：{{ shiTingItem.dubName }}</view>
				</view>
				<view class="right">
					<view class="btn del" @tap="removeShiTingItem()">
						<image class="icon" :src="imgPath + 'createAvatar/delAudio.svg'" mode=""></image>
					</view>
				</view>
			</view>
			<view class="controls">
				<!-- <audio class="audioEl" :autoplay="true" ref="audioEl" @pause="removeShiTingItem" :src="shiTingItem.audioSrc" :name="selectItem.dubName" controls :loop="true"></audio> -->
			</view>
		</view>
	</view>
</template>

<script>
import * as api from "@/api/createVideo.js";
let timer = null;
import { tools } from "@/utils/util";
export default {
	name: "PickSpeaker",
	props: {
		pageShow: {
			type: Boolean,
			default: true
		},
		show: {
			type: Boolean,
			default: false
		},
		promiseRes: {
			type: Object | Function,
			default() {
				return null;
			}
		},
		selectItem: {
			type: Object,
			default() {
				return {};
			}
		},
		pageItem: {
			type: Object,
			default() {
				return {};
			}
		},
		content: {
			type: String,
			default() {
				return "你能看出我是AI吗？现在你看到的我其实并不是真实的我，而是我的数字分身";
				return "随着技术不断发展，" + tools.companyName + "数字人在电商、直播、娱乐、教育、广告等领域的应用越来越广泛";
			}
		}
	},
	data() {
		return {
			imgPath: tools.imgPath,
			companyName: tools.companyName,
			tabbarAc: 1,
			speed: 1.05,
			pitch: 0,
			volume: 100,
			tabbarList: [],
			tabbarAc2: null,
			tabbarList2: [],
			yushe: [],
			yusheCurrent: 1,
			yusheSize: 21,
			yusheTotal: null,
			geren: [],
			gerenCurrent: 1,
			gerenSize: 21,
			gerenTotal: null,
			contentList: [],
			shiTingItem: {},
			audioListLeft1: ""
		};
	},
	async created() {
		console.log("created");
		this.initTabbarList();
		this.initAudioContext();
		let next = await this.initGetData();
		this.pickContentItem({
			item: this.yushe[0],
			index: 0
		});
		if (this.promiseRes) {
			this.promiseRes(true);
		}
	},
	destroyed() {
		console.log("destroyed");
	},
	methods: {
		// AudioContext初始化
		initAudioContext() {
			if (!this.audioContext) {
				let audioContext = uni.createInnerAudioContext();
				audioContext.autoplay = true;
				audioContext.loop = true;
				audioContext.volume;
				this.audioContext = audioContext;
			}
		},
		// 修改音量
		async changeVolumesize(e) {
			this.volume = e.detail.value;
			this.$emit("changeVolume", this.volume);
			this.audioContext.volume = this.volume * 0.01;
		},
		// 修改语速
		async changeSpeedsize(e) {
			this.speed = e.detail.value;
			this.$emit("changeSpeed", this.speed);

			let item = this.yushe.find((item) => item.dubId == this.shiTingItem.dubId);
			if (!item) return;
			this.removeShiTingItem();
			uni.showLoading({
				title: "请稍后"
			});
			let res = await api.postAudioTTS({
				speaker: item.thirdpartyId,
				text: this.content.length > 20 ? this.content : "随着技术不断发展，" + this.companyName + "数字人在电商、直播、娱乐、教育、广告等领域的应用越来越广泛",
				text: this.content.length > 20 ? this.content : "你能看出我是AI吗？现在你看到的我其实并不是真实的我，而是我的数字分身",
				pitch: this.pitch,
				speed: this.speed
			});
			uni.hideLoading();
			if (!res) {
				this.shiTingItem = {};
			}
			this.shiTingItem = item;
			this.shiTingItem.audioSrc = res.data;
			this.audioContext.src = res.data;
		},
		// 修改语调
		async changePitchsize(e) {
			this.pitch = e.detail.value;
			this.$emit("changePitch", this.pitch);

			let item = this.yushe.find((item) => item.dubId == this.shiTingItem.dubId);
			if (!item) return;
			this.removeShiTingItem();
			uni.showLoading({
				title: "请稍后"
			});
			let res = await api.postAudioTTS({
				speaker: item.thirdpartyId,
				text: this.content.length > 20 ? this.content : "随着技术不断发展，" + this.companyName + "数字人在电商、直播、娱乐、教育、广告等领域的应用越来越广泛",
				text: this.content.length > 20 ? this.content : "你能看出我是AI吗？现在你看到的我其实并不是真实的我，而是我的数字分身",
				pitch: this.pitch,
				speed: this.speed
			});
			uni.hideLoading();
			if (!res) {
				this.shiTingItem = {};
			}
			this.shiTingItem = item;
			this.shiTingItem.audioSrc = res.data;
			this.audioContext.src = res.data;
		},
		// 播放暂停背景音乐
		playBgm(flag) {
			return;
			let bgmAudioEl = this.$refs.bgmAudioEl.$el;
			// console.log([bgmAudioEl])
			if (flag) {
				bgmAudioEl.play();
			} else {
				bgmAudioEl.pause();
			}
		},
		// 滚动事件(做懒加载)
		contentListScroll(event) {
			const that = this;
			if (timer) clearTimeout(timer);
			timer = setTimeout(() => {
				if (that.tabbarAc == 1) {
					if (this.yusheTotal === this.yushe.length) return;
					this.yusheCurrent++;
					this.getDataApi();
				} else {
					if (this.gerenTotal === this.geren.length) return;
					this.gerenCurrent++;
					this.getDataApi2();
				}
				clearTimeout(timer);
				timer = null;
			}, 300);
		},
		// 获取公共数据分类api
		async getSysmatTwoType() {
			const type = "music";
			let res = await api.getLingyu();
			if (!res) return;
			res.data.splice(1, 0, {
				id: "",
				fieldName: "全部"
			});
			this.tabbarList2 = res.data;
			this.tabbarAc2 = this.tabbarList2[0].id;
			return true;
		},
		// 秒转时间(s=>mm:ss)
		seconds2time(seconds) {
			seconds = seconds.toFixed(0);
			return `${Math.floor(seconds / 60)
				.toString()
				.padStart(2, 0)}:${(seconds % 60).toString().padStart(2, 0)}`;
		},
		// 获取公共数据api
		async getDataApi(_id) {
			let res = null;
			let data = {
				content: "",
				field: this.tabbarAc2,
				currentPage: this.yusheCurrent,
				pageSize: this.yusheSize
			};
			res = await api.getAudioManOfPage(data);
			if (!res?.data?.source) {
				this.yushe = [];
				this.yusheTotal = null;
				return;
			}
			this.yusheTotal = res.data.totalSource;
			let yushe = res.data.source.map((e) => ({
				...e,
				picSrc: e.headerImg,
				duration: 0,
				durationStr: "00:00"
			}));
			this.yushe = [...this.yushe, ...yushe];
			return true;
		},
		// 获取私有数据api
		async getDataApi2() {
			let res = await api.getUserSource("music");
			if (!res) return;
			let geren = res.data.map((e) => {
				let duration = JSON.parse(e.payLoad)?.matterValue ?? 0;
				return {
					...e,
					picSrc: e.theCover,
					duration: duration,
					durationStr: this.seconds2time(duration)
				};
			});
			this.geren = geren;
			return true;
		},
		// 获取后端数据
		async initGetData() {
			let getData = new Promise(async (next) => {
				let flag = await this.getSysmatTwoType();
				if (!flag) return;
				let flag2 = await this.getDataApi();
				if (!flag2) return;
				next(true);
			});
			await Promise.all([getData]);
			return true;
		},
		// 初始化contentList
		initContentList() {
			this.contentList = matData.map((e) => ({
				...e,
				picSrc: e.theCover
			}));
		},
		// 初始化tabbarList
		initTabbarList() {
			this.tabbarList = [
				{
					text: "预设",
					id: 1
				},
				{
					text: "本地",
					id: 2
				}
			];
		},
		// 切换类型
		changeTabbarAc({ item, index }) {
			this.tabbarAc = item.id;
			if (this.tabbarAc == 2) {
				//获取私有数据
				this.getDataApi2();
			}
		},
		//切换数据子类型
		async changeTabbarAc2({ item, index }) {
			this.tabbarAc2 = item.id;
			this.yushe = [];
			this.yusheCurrent = 1;
			this.yusheTotal = null;
			this.audioListLeft1 = "";
			let next = await this.getDataApi();
			await new Promise((r) => {
				this.$nextTick(() => {
					setTimeout(() => {
						this.audioListLeft1 = "audioItem" + this.selectItem.dubId;
						r(true);
					}, 688);
				});
			});
			return true;
		},
		//选择item
		pickContentItem({ item, index }) {
			if (item?.dubId == this.selectItem?.dubId) {
				this.removeContentItem();
				return;
			}
			this.$emit("pickSpeaker", {
				item,
				index
			});
		},
		// 去除item
		removeContentItem() {
			this.$emit("removeSpeaker");
		},
		//选择试听item
		async pickShiTingItem({ item, index }) {
			if (item.dubId == this.shiTingItem.dubId) {
				this.removeShiTingItem();
				return;
			}
			uni.showLoading({
				title: "请稍后"
			});
			console.log("选择试听item");
			let res = await api.postAudioTTS({
				speaker: item.thirdpartyId,
				text: this.content.length > 20 ? this.content : "随着技术不断发展，" + this.companyName + "数字人在电商、直播、娱乐、教育、广告等领域的应用越来越广泛",
				text: this.content.length > 20 ? this.content : "你能看出我是AI吗？现在你看到的我其实并不是真实的我，而是我的数字分身",
				pitch: this.pitch,
				speed: this.speed
			});
			uni.hideLoading();
			if (!res) {
				this.shiTingItem = {};
			}
			this.shiTingItem = item;
			this.shiTingItem.audioSrc = res.data;
			this.audioContext.src = res.data;
		},
		// 去除试听item
		removeShiTingItem() {
			this.audioContext.pause();
			this.shiTingItem = {};
		}
	},

	watch: {
		async pageShow(val) {
			if (val) {
				await this.changeTabbarAc2({
					item: this.tabbarList2[0],
					index: 0
				});
				this.$emit("pickSpeaker", {
					item: this.yushe[0],
					index: 0
				});
			}
		},
		async show(val) {
			if (!val) {
				this.removeShiTingItem();
				this.audioListLeft1 = "";
			} else {
				if (this.selectItem && this.selectItem.dubId) {
					if (this.yushe.find((e) => e.dubId == this.selectItem.dubId)) {
						this.audioListLeft1 = "audioItem" + this.selectItem.dubId;
					} else {
						let item = null;
						if (this.tabbarAc2 == "") {
							item = this.tabbarList2[0];
						} else {
							item = this.tabbarList2[1];
						}
						if (!item) return;
						this.changeTabbarAc2({
							item: item
						});
					}
				}
			}
		},
		["pageItem.ac"](val) {
			if (val != 7) {
				this.removeShiTingItem();
				return;
			}
			this.$emit("changeMyDH", 46);
		}
	}
};
</script>

<style lang="scss">
.pick-speaker {
	display: flex;
	flex-direction: column;
	overflow: hidden;
	height: 100%;

	.main-tabbar {
		display: -webkit-box;
		overflow: auto;

		.tabbar-item {
			padding: 0.5vw 1vw;
			color: rgba(255, 255, 255, 0.36);
			display: flex;
			justify-content: center;
			align-items: center;
			border-radius: 100vw;
			background: rgba(255, 255, 255, 0.125);
			margin: 0vw 5vw 2vw 0vw;
			min-width: 10vw;

			&.ac {
				border: 2px solid rgba(0, 153, 127, 1);
				.text {
					color: rgba(0, 153, 127, 1);
					font-weight: 700;
				}
			}

			.text {
				font-size: 24rpx;
				font-weight: 400;
			}
		}
	}

	.main-content {
		flex: 1;
		overflow: hidden;
		display: flex;
		flex-direction: column;
		.scroll_view {
			width: 100%;
			height: 36vh;
			display: flex;
			overflow: hidden;
		}

		.audio-list {
			flex: 1;
			// width: max-content;
			// display: -webkit-box;
			width: 100%;
			display: grid;
			grid-template-columns: repeat(3, 1fr);
			gap: 0vw;
			text-align: center;
			overflow: hidden;

			.audio-item {
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				padding: 2vw 1vw;
				height: max-content;
				border-radius: 1.5vw;

				&.ac {
					border: 1px solid #00deb9;
				}

				.left {
					display: flex;
					justify-content: center;
					align-items: center;
					flex-direction: column;
					height: 100%;

					.pic-box {
						width: 20vw;
						height: 100%;
						position: relative;
						display: flex;
						justify-content: center;
						align-items: center;

						.audio-pic {
							width: 15vw;
							height: 15vw;
							display: block;
							border-radius: 50%;
						}

						.playStatusIcon {
							position: absolute;
							left: 0vw;
							top: 0vw;
							width: 100%;
							height: 100%;
							display: flex;
							justify-content: center;
							align-items: center;

							.icon {
								width: 8.6vw;
								height: 8.6vw;
								display: block;
							}
						}
					}

					.date-time {
						font-size: 3vw;
						width: 100%;
						height: 100%;
						display: flex;
						flex-direction: column;
						justify-content: center;
						overflow: hidden;
						.date {
							width: 22vw;
							align-items: center;
							overflow: hidden;
							white-space: nowrap;
							text-overflow: ellipsis;
						}
					}

					.useBtn {
						margin-top: 2vw;
						background: linear-gradient(270deg, #00deb9 0%, #7affe9 100%);
						display: flex;
						justify-content: center;
						align-items: center;
						border-radius: 100vw;
						padding: 1vw 2vw;

						.useBtn-text {
							font-size: 3vw;
							color: #111;
						}
					}
				}

				.right {
					display: none;
					justify-content: center;
					align-items: center;
					height: 100%;

					.time {
					}

					.icon {
						width: 5vw;
						height: 5vw;
						display: block;
						padding: 0vw 3vw;
					}

					.useBtn {
						background: linear-gradient(270deg, #00deb9 0%, #7affe9 100%);
						display: flex;
						justify-content: center;
						align-items: center;
						border-radius: 100vw;
						padding: 1vw 2vw;

						.useBtn-text {
							font-size: 3.5vw;
							color: #111;
						}
					}
				}
			}
		}

		.audio-list-kong {
			height: 36vh;
			width: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
			.text {
				color: #fff;
				font-size: 4.6vw;
			}
		}

		.textStyle {
			margin-top: calc(2vh + 3vw);
			flex: 1;
			overflow: auto;

			.textStyle-item {
				width: 100%;
				display: flex;
				align-items: center;
				padding: 1.68vw 0vw;

				.label {
				}

				.r-c {
					margin-left: 3vw;
					flex: 1;

					&.picker-box {
						box-sizing: border-box;
						padding: 2vw;
						background: #506768;
						color: #fff;
						border: 1px solid transparent;
						border-radius: 2vw;
						position: relative;
						display: flex;
						align-items: center;

						.picker {
							flex: 1;
						}

						.arrow {
							position: absolute;
							right: 2vw;
							width: 3vw;
							height: 3vw;

							.icon {
								width: 100%;
								height: 100%;
								display: block;
							}
						}
					}

					&.input-box {
						box-sizing: border-box;
						padding: 2vw;
						background: #506768;
						color: #fff;
						border: 1px solid transparent;
						border-radius: 2vw;
					}

					&.btns-box {
						display: flex;
						justify-content: space-around;
						align-items: center;

						.btn-item {
							padding: 2vw;
							background: #506768;
							color: #fff;
							border: 1px solid transparent;
							border-radius: 1vw;

							&.ac {
								opacity: 1;
								border-radius: 4px;
								background: rgba(0, 153, 127, 0.2);
								border: 1px solid #00997f;
							}
						}
					}

					&.color-show {
						flex: none;
						width: 30vw;
						height: 10vw;
						box-sizing: border-box;
						padding: 2vw;
						border: 1px solid transparent;
						border-radius: 2vw;
						position: relative;
						overflow: hidden;

						.box {
							position: absolute;
							left: 0vw;
							top: 0vw;
							width: 100%;
							height: 100%;
							background: rgba(80, 103, 104, 0.2);
						}
					}

					&.slider-box {
						.slider {
							margin-top: 0vw;
							margin-bottom: 0vw;
						}
					}
				}
			}
		}
	}

	.main-selectItem {
		.item-info {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.left {
				display: flex;
				justify-content: center;
				align-items: center;

				.pic {
					margin-right: 2vw;

					.audio-pic {
						width: 10vw;
						height: 10vw;
						border-radius: 50%;
						display: block;
					}
				}

				.text {
				}
			}

			.right {
				.btn {
					.icon {
						width: 5vw;
						height: 5vw;
						display: block;
					}
				}
			}
		}

		.controls {
			width: 100%;

			.audioEl {
				width: 100%;
			}

			.btns {
				display: flex;

				.btn {
					background: linear-gradient(270deg, #00deb9 0%, #7affe9 100%);
					color: #111111;
					border-radius: 100vw;
					display: flex;
					justify-content: center;
					align-items: center;
					margin-left: 2vw;
					padding: 1vw 2vw;
					font-size: 17px;
				}
			}
		}
	}
}
</style>
